/**
 * 创建拍照室
 * MediaSourceTrack API 只有最新版的Chrome 支持
 */

function hasUserMedia() {
    return !!(navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia) ;
}

if(hasUserMedia()){
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia ;
    // 根据不同的浏览器 设置不同的分辨率和其他参数值
    var video = document.querySelector('video'),
        canvas = document.querySelector('canvas'),
        streaming = false ;
       navigator.getUserMedia(
                             {video:true,audio:false},
                             function(stream){
                             video.src = window.URL.createObjectURL(stream); // 函数将流加载到video元素中
                                 streaming =  true ;
                             },function (error) {
                                console.log(" Raised an error when capturiing:",error);
                             });

        document.querySelector("#capture").addEventListener('click',function (event) {
            if(streaming){
                canvas.width = video.clientWidth ;
                canvas.height = video.clientHeight ;
                var context = canvas.getContext('2d');
                context.drawImage(video,0,0);
            }
        });

    // 当用户单击是 新增滤镜
    var filters = ['','grayscale','sepia','invert'] ,
        currentFilter = 0 ;
    
    document.querySelector("video").addEventListener('click',function () {
        if(streaming){
            canvas.width = video.clientWidth ;
            canvas.height = video.clientHeight ;
            var context = canvas.getContext('2d');
            // 给照片添加文字
            context.fillStyle = "red" ;
            context.fillText=("hello-word",0,0);

            context.drawImage(video,0,0);
            currentFilter ++ ;
            if(currentFilter > filters.length - 1) currentFilter = 0;
            canvas.className = filters[currentFilter];


        }
    });

}else{
    alert('抱歉您的浏览器不支持');
}